package com.kxmall.web.controller.task;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author kaixin
 * @version 1.0
 * @date 2022/11/16
 */

@Component
public class InitSqlTask {


    //每天凌晨初始化脚本
    //@Scheduled(cron = "0 0 1 * * *")
    public void mulitSqlForIbatisOnMySql() {
        Connection conn = null;
        try {
            //执行sql语句报错时文件配置
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            //获取数据源
            conn = DriverManager.getConnection("jdbc:mysql://116.62.17.100/cs?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true&useSSL=false", "root", "xxxx");
            //创建脚本执行对象
            ScriptRunner r = new ScriptRunner(conn);
            ClassPathResource classPathResource = new ClassPathResource("init/kxmall-github.sql");
            r.runScript(new BufferedReader(new InputStreamReader(classPathResource.getInputStream(), "UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != conn)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }

}
